<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\DB;

class Users extends Model
{
    use Notifiable;
    // 用户表
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $tran_status = true;
    protected $dateFormat = 'U';
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i',
        'updated_at' => 'datetime:Y-m-d H:i'
    ];

    /**
     * 用户注册
     * @param $data
     * @return array
     */
    public function register($data){
        $exist = $this::where('account',$data['account'])->first();
        if ($exist){
            return ['success' => false, 'msg' => '该账户名已存在！'];
        }
        $this->account = $data['account'];
        $this->user_name = $data['user_name'];
        $this->safe_key = createSafeKey();
        $this->password = Md5Pass($this->safe_key,$data['password']);
        $result = $this->save();
        if ($result){
            return ['success' => true, 'msg' => '注册成功，去登录吧'];
        }else{
            return ['success' => false, 'msg' => '注册失败，请稍后再试！'];
        }
    }

    public function login($data, $ip){
        // 开启事务
        DB::beginTransaction();
        $user = $this::where('account',$data['account'])->first();
        if (!$user){
            return ['success' => false, 'msg' => '用户不存在','user' => $user];
        }
        if (Md5Pass($user->safe_key,$data['password']) !== $user->password){
            return ['success' => false, 'msg' => '密码错误','user' => $user];
        }

        // token更新
        $token = new UserToken;
        $token_ex = $token::where('user_id',$user->id)->first();
        if ($token_ex){
            $token = $token_ex;
        }
        $token->ip = $ip;
        $token->user_id = $user->id;
        $token->overtime = time() + 3600*24*7;
        $token->token = createToken();
        if (!$token->save()){
            $this->tran_status = false;
        }
        $user->token = $token->token;
        if (!$user->save()){
            $this->tran_status = false;
        }
        if ($this->tran_status == false){
            DB::rollBack();
            return ['success' => false, 'msg' => '登陆失败','user' => $user];
        }else{
            DB::commit();
            return ['success' => true, 'msg' => '登录成功','user' => $user];
        }
    }

    /**
     * 获取通知发送频道
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return $notifiable->prefers_sms ? ['nexmo'] : ['mail', 'database'];
    }
}
